package base.thread_demo.demo11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 可重入锁演示: main线程持有lock锁，后续main执行到m1、m2,发现还需要再次持有lock锁，
 * 因为同是main线程调用，可以再次持有lock锁，进而执行m1、m2逻辑
 *
 */
public class ReentrantLockDemo01 {
    private static final Logger log = LoggerFactory.getLogger(ReentrantLockDemo01.class);

    /**
     * 该对象等价于Java对象上挂的操作系统层面的 Monitor对象,ReentrantLock是Java从语法层面上提供的不依赖于
     * 操作系统 Monitor的实现
     */
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        lock.lock();
        try {
            log.info("{} run.......", Thread.currentThread().getName());
            m1();
        }finally {
            log.info("{} unlock", Thread.currentThread().getName());
            lock.unlock();
        }
    }


    public static void m1() {
        lock.lock();
        try {
            log.info("{}-> m1 run......", Thread.currentThread().getName());
            m2();
        }finally {
            log.info("{}-> m1 unlock", Thread.currentThread().getName());
            lock.unlock();
        }
    }

    public static void m2() {
        lock.lock();
        try {
            log.info("{}-> m2 run......", Thread.currentThread().getName());
        }finally {
            log.info("{}-> m2 unlock", Thread.currentThread().getName());
            lock.unlock();
        }
    }
}
